package com.ebraga.trackerclub.android.util;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;

import org.apache.commons.lang.StringUtils;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.Vibrator;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.webkit.WebView;
import android.widget.Toast;

import com.ebraga.trackerclub.android.R;
import com.ebraga.trackerclub.android.exception.handler.BackofficeHandlerException;
import com.ebraga.trackerclub.android.handler.service.LoginServiceHandler;
import com.ebraga.trackerclub.android.util.api.AndroidContext;
import com.ebraga.trackerclub.android.util.core.AndroidContextImpl;
import com.ebraga.trackerclub.android.view.LoginActivity;
import com.ebraga.trackerclub.android.vo.UserVO;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

public class UtilView extends Activity {

	// Start synch/update service every 15 minutes (in millisec)
	public static final long INTERVAL_SYNCH = 1000L * 60 * 15;
	public static final long INTERVAL_POSTPONE = 1000L * 60 * 60 * 3; // 3 hours
	private final long WAIT_TIME = 10000;

	// TODO: Flag is only used for loading screen? -> remove
	private static boolean connectedToNetworkFlag = false;

	private static enum Connection { WIFI, DATA, NONE }
	private static Connection currentConnection = Connection.NONE;
	
	private ProgressDialog ringProgressDialog;
	
//	private static long timeOfLastAction;
	
	/**
	 * When showing an important Toast (or an Alert), attract the user's attention 
	 * by vibrating. 
	 */
	static public void vibrate(Context context) {
		Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
		v.vibrate(new long[]{ 250, 250, 500 }, -1);
	}	


	public static void sendNotification(Context context, String message, Integer idNotification) {
		sendNotification(context, message, true, idNotification);
		
	}		
	
	/**
	 * Send notification
	 * @param context
	 * @param message
	 */
	public static void sendNotification(Context context, String message) {
		sendNotification(context, message, true);
	}

	/**
	 * Send notification
	 * @param context
	 * @param message
	 * @param vibrate
	 * @param idNotification
	 */
	public static void sendNotification(Context context, String message, boolean vibrate, Integer idNotification) {
		String titleNotification = context.getString(R.string.app_name);
		sendNotification(context, titleNotification, message, vibrate, idNotification);

	}	
	
	/**
	 * Send notification
	 * @param context
	 * @param message
	 * @param vibrate
	 */
	public static void sendNotification(Context context, String message, boolean vibrate) {
		String titleNotification = context.getString(R.string.app_name);
		sendNotification(context, titleNotification, message, vibrate, null);

	}

	/**
	 * Send notification
	 * @param context
	 * @param message
	 */	
	public static void sendNotification(Context context, String title, String message) {
		sendNotification(context, title, message, true, null);
	}
	
	@SuppressWarnings("deprecation")
	private static void sendNotification(Context context, String title, String message, boolean vibrate, Integer idNotification) {
		
		NotificationManager mNotificationManager;
		
		CharSequence contentTitle = title;
		CharSequence contentText = message;
		String notify = context.getString(R.string.notify_text);

		mNotificationManager = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
		Notification notifyDetails = new Notification(R.drawable.actionbar_icon, notify, System.currentTimeMillis());

		notifyDetails.setLatestEventInfo(context, contentTitle, contentText, null);
		
		PendingIntent p = PendingIntent.getActivity(context, 0, new Intent(context, LoginActivity.class), 0);  
		//notifyDetails.setLatestEventInfo(context, message, notify, p);  
		notifyDetails.setLatestEventInfo(context, contentTitle, contentText, p);
		
		if (idNotification == null) {
			mNotificationManager.notify(nextNotificationId(context), notifyDetails);
		} else {
			mNotificationManager.notify(idNotification, notifyDetails);
		}

		if (vibrate) {
			vibrate(context);
		}

	}	 

	private static int nextNotificationId(Context context) {

		AndroidApplication androidApplication  = (AndroidApplication) context.getApplicationContext();
		int notificationId = 0;
		if (androidApplication != null) {
			notificationId = androidApplication.getNotificationId();
			androidApplication.setNotificationId(androidApplication.getNotificationId() + 1);
		}
		
		return notificationId;
	}

	public static void showMessage(WebView webView, String message) {
		showMessage(webView, message, true);
	}
	
	
	public static void showMessage(WebView webView, String message, boolean vibrate) {
		String textMessage =  getTextMessage(webView.getContext(), message);
		webView.loadUrl("javascript:showMessage(" + textMessage + ")");
		if (vibrate) {
			vibrate(webView.getContext());
		}

	}

	public static void showMessage(Context context, String message) {
		showMessage(context, message, true);
	}
	
	public static void showMessage(Context context, String message, boolean vibrate) {
		String textMessage =  getTextMessage(context, message);
		Toast.makeText(context, textMessage, Toast.LENGTH_LONG).show();
		if (vibrate) {
			vibrate(context);
		}

	}    

	public static void showMessage(WebView webView, Context context, String message) {
		showMessage(webView, context, message, true);
	}
	
	public static void showMessage(WebView webView, Context context, String message, boolean vibrate) {
		String textMessage = getTextMessage(context, message);

		webView.loadUrl("javascript:showMessage(" + textMessage + ")");
		Toast.makeText(context, textMessage, Toast.LENGTH_LONG).show();
		if (vibrate) {
			vibrate(context);
		}

	}

	/*
	 * Procura mensagem no arquivo string.xml, caso não encontre retorna a mensagem original
	 */
	public static String getTextMessage(Context context, String message) {
		String textMessage;
		try {

			textMessage = context.getString(context.getResources().getIdentifier(message, "string", context.getPackageName()));

		} catch (Exception e) {

			textMessage = message;

		}

		if (textMessage == null || textMessage.equals("")) {
			context.getString(context.getResources().getIdentifier(ISmartServiceConstants.ERROR_CODE.GENERIC_ERROR, "string", context.getPackageName()));
		}

		return textMessage;
	}

	/**
	 * Return Sim Serial Number
	 * @param context
	 * @return
	 */
	public static String getSimSerialNumber(Context context){
		TelephonyManager mTelephonyMgr;
		mTelephonyMgr = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); 
		
		return mTelephonyMgr.getSimSerialNumber();
	}
	
	
	/**
	 * Return Device ID Number
	 * @param context
	 * @return
	 */
	public static String getDeviceId(Context context) {
		// GET DEVICE ID
		return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
	}

	/**
	 * Return Device IMEI Number
	 * @param context
	 * @return
	 */
	public static String getIMEINumber(Context context) {
		// GET IMEI NUMBER     
		TelephonyManager tManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String deviceIMEI = tManager.getDeviceId();  

		return deviceIMEI;
	}    

	/**
	 * Method setting the connectedToNetworkFlag for later use and returning it
	 * Called regularly from AlarmReceiver or NetworkStateReceiver + every time Synch/Update is called from UI
	 * 
	 * @param context
	 * @return
	 */
	public static boolean connectedToNetwork(Context context) {
	    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
	    android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

	    if (null != wifi && wifi.isConnected()) {
	    	connectedToNetworkFlag = true;
	    	currentConnection = Connection.WIFI;
	    } else if (null != mobile && mobile.isConnected()) {
	    	connectedToNetworkFlag = true;
	    	currentConnection = Connection.DATA;
	    } else {
	    	connectedToNetworkFlag = false;
	    	currentConnection = Connection.NONE;
	    }
	    return connectedToNetworkFlag;
	}

	public static boolean connectedToWiFi(Context context) {
	    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

	    return null != wifi && wifi.isConnected();
	}

	public static boolean connectedToMobileNetwork(Context context) {
	    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

	    return null != mobile && mobile.isConnected();
	}	
	

	public static boolean getConnectedToNetworkFlag() {
		return connectedToNetworkFlag;
	}
	
	public static boolean gpsActived(Context context) {
		LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		
		if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			return true;
		} else {
			return false;
		}

		
	    
	}	
	
	public static UserVO getLastUserSession(Context context) {
		UserVO userVO = null;
		
		AndroidContext androidContext = new AndroidContextImpl();
		androidContext.setContext(context.getApplicationContext());						
		LoginServiceHandler loginServiceHandler = new LoginServiceHandler(androidContext);
		try {
			userVO = loginServiceHandler.lastLogin();
		} catch (BackofficeHandlerException e) {
			DLog.e(e);
		}
		
		return userVO;
	}
	
	public static UserVO getUserSession(Context context) {
		UserVO userVO = null;
		
    	AndroidApplication androidApplication = (AndroidApplication) context.getApplicationContext();
    	
    	if (androidApplication != null && androidApplication.getUserVO() != null) {
    		userVO = (UserVO) androidApplication.getUserVO();	
    	}
    	
    	//Garantir que retorne os dados do último usuário logado, mesmo que a contexto da aplicação tenha perdido a informação.
    	if (userVO == null) {
    		userVO = getLastUserSession(context);
    	}
    	
    	return userVO;
	}
	
	public void showWaitMessage(Context context) {
		showWaitMessage(context, WAIT_TIME);
	}

	public void showWaitMessage(Context context, final long time) {
		
		try{
			String wait 	= getTextMessage(context, ISmartServiceConstants.WARN_CODE.WARN_WAITTING);
			String proccess = getTextMessage(context, ISmartServiceConstants.WARN_CODE.WARN_INPROCESS);
			
			ringProgressDialog = ProgressDialog.show(context, wait, proccess, true);

			ringProgressDialog.setCancelable(true);
			
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						// Here you should write your time consuming task...
						// Let the progress ring for 10 seconds...
						Thread.sleep(time);
					} catch (Exception e) {

					}
					ringProgressDialog.dismiss();
				}
			}).start();
			

		} catch (Exception e) {
			DLog.d(e.getMessage());
		}		
		
	}
	
	public void hideWaitMessage() {
		try{
			ringProgressDialog.dismiss();
		} catch (Exception e) {
			DLog.d(e.getMessage());
		}			 
	}		
	

	/**
	 * Method responsible to generate HTTPBasicAuthFilter using UserVO fields. 
	 * @param userVO
	 * @return
	 */
	public static HTTPBasicAuthFilter buildHTTPBasicAuthFilter(UserVO userVO) {
		String imei = StringUtils.rightPad(userVO.getImei(), 20, ' ');		
				
		String password = imei;
		
		return new HTTPBasicAuthFilter(userVO.getImei(), password);
		
	}
	

    public static boolean checkRestriction(Context context) {
    	
        boolean isValid = true;
        /*
		if (!UtilView.connectedToNetwork(getBaseContext())) {
			UtilView.sendNotification(getBaseContext(), getString(R.string.warn_internet_off));
			isValid = false;
		}
		*/
		
		if (!UtilView.gpsActived(context)) {
			UtilView.sendNotification(context, context.getString(R.string.warn_gps_off), ISmartServiceConstants.NOTIFICATION_ID.GPS_DISABLED);
			isValid = false;
		}	        
		
		return isValid;
        
    }

    public static double doubleFormat(double value) {
    	DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(java.util.Locale.US);
    	DecimalFormat newFormat = new DecimalFormat("###.#");
    	newFormat.setDecimalFormatSymbols(decimalFormatSymbols);
    	String decimal =  newFormat.format(value);
    	
    	return new Double(decimal);
    }

}